import { message, Spin, Button } from 'antd'
import { Actionable } from '@/desktop/components'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { GroupContact, GroupExtra } from '@/services/contact-types/groups'
import { ContactType } from '@/services/contacts'
import ChatFlow from '../external-info/chat-flow'
import EditInfo, { type GroupEditInfo } from './edit'
import GroupTags from './tags'
import './index.module.less'

export default function GroupInfo() {
  const [current] = useStreams(services.contacts.current.contact)
  return current?.type === ContactType.group ? <GroupInfoContent group={current} /> : null
}

function GroupInfoContent(props: { group: GroupContact }) {
  const { group } = props

  const [extra, setExtra] = useState<GroupExtra | null>(null)
  const loadExtra = useCallback(async () => {
    const res = await services.groups.getExtra(group.id)
    if (res.success) setExtra(res.data)
    else void message.warning('群资料加载失败')
  }, [group])
  useEffect(() => void loadExtra(), [loadExtra])

  const [editing, setEditing] = useState<GroupEditInfo | null>(null)
  const startEdit = useCallback(
    () => extra && setEditing({ ...extra, remark: group.remark }),
    [extra, group],
  )
  const finishEdit = useCallback(() => {
    setEditing(null)
    void loadExtra()
  }, [loadExtra])

  const spin = <Spin />
  const empty = <div styleName="empty">无</div>

  return <div styleName="group-info-panel">
    <Actionable>
      <header>
        <Button type="link" onClick={startEdit}>
          编辑群资料
        </Button>
      </header>
    </Actionable>

    <section>
      <label>群名称</label>
      <div>{group.name}</div>
    </section>

    <section>
      <label>群备注</label>
      <div>{group.remark || empty}</div>
    </section>

    <section>
      <label>群描述</label>
      <div styleName="describe">{extra ? extra.describe || empty : spin}</div>
    </section>

    <section>
      <label>群标签</label>
      <GroupTags groupId={group.id} />
    </section>

    <Actionable>
      <ChatFlow contactId={group.id} forGroup={true} styleName="chat-flow" />
    </Actionable>

    <EditInfo editing={editing} onFinish={finishEdit} />
  </div>
}
